import axios from 'axios'
import { tokenStore } from '../store/token'
import { ElMessage } from 'element-plus'

const instance = axios.create({
    //请求的基础路径
    // baseURL:"https://api.umog.com/"
    // baseURL: 'http://localhost:8023',
    // 更改baseURL
    baseURL: '/api',
    timeout: 100000
})

//设置请求拦截器
instance.interceptors.request.use(
    (config) => { 
        console.log("请求前拦截器")
        //设置token头
        const tokenStore = tokenStore()
        if(tokenStore.token) {
            config.headers.Authorization = tokenStore.token
        }
        return config
    },

    (error) => { 
        console.log("请求前拦截器异常方法")
        //返回一个失败状态的 promise
        return Promise.reject(error)
    }
)

instance.interceptors.response.use(
    (response) => {
        // console.log("axios-response: ")
        // console.log(response)
        if (response.data.code === 1) {
            return response
        }
        // 操作失败
        ElMessage({
            message: response.data.msg ? response.data.msg : '服务异常',
            type: 'error',
            plain: true,
            showClose: true
        })
        return Promise.reject(response)
    },
    (err) => {
      ElMessage({ message: err.response.data.message || '服务异常', type: 'error' })
      console.log(err)
      if (err.response?.status === 401) {
        router.push('/login')
      }
      return Promise.reject(err)
    }
)
  
// //使用默认导出暴露 instance

export default instance